package concurrent

import (
	"fmt"
	"time"
)

func goroutineTask() {
	messageChan := make(chan int, 1)
	for i := 1; i < 5; i++ {
		go func(i int) {
			preIndex := 0
			if i > 1 {
				preIndex = <-messageChan
			}
			fmt.Printf("当前值：%d，来源值：%d\n", i, preIndex)
			messageChan <- i
		}(i)
	}
	time.Sleep(time.Second * 1)
}

func selectTask() {
	c1 := make(chan int)
	c2 := make(chan int)
	go func() {
		time.Sleep(time.Second * 4)
		c1 <- 213
	}()
	go func() {
		time.Sleep(time.Second * 2)
		c2 <- 456
	}()
	// 注意点，for + select 配合使用时，break、return、continue只能跳出select
	for {
		select {
		case value := <-c1:
			fmt.Println("从c1读到了", value)
		case v2 := <-c2:
			fmt.Println("从c2读到了", v2)
		case <-time.After(time.Second * 3):
			fmt.Println("timeout")
			goto END
		}
	}
END:
	fmt.Println("终于逃出生天")
}
